// mircoApp/cloud_shop/customersDetail/customersDetail.js
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    active: 1,
    active_child: 0,
    info: [],
    dataList: [],
    page: 1,
    total_page: 0,
    isLoadMore: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let language = wx.getStorageSync("langIndex");
    this.setData({
      active: 1,
      language: language.en,
    });
    this.getData();
    this.init();
    this.getChildData();
  },
  tapCall(e) {
    wx.makePhoneCall({
      phoneNumber: this.data.info.has_one_member.mobile,
    });
  },
  toGood(e) {
    let { item } = e.currentTarget.dataset;
    wx.navigateTo({
      url: "/packageA/detail_v2/detail_v2?id=" + item.id,
    });
  },
  toGoodDetail(e) {
    let { item } = e.currentTarget.dataset;
    if (this.data.active_child == 3) {
      wx.navigateTo({
        url: "/packageG/pages/buy/cart_v2/cart_v2",
      });
      return;
    }
    // 其他跳去订单列表
    wx.navigateTo({
      url: `/packageA/member/orderdetail/orderdetail?order_id=${item.id}&orderType=cloud_shop`,
    });
  },
  todayChange(e) {
    let { key } = e.currentTarget.dataset;
    this.setData({
      active: key,
    });
    this.getData();
  },
  init() {
    this.setData({
      dataList: [],
      page: 1,
      total_page: 0,
      isLoadMore: true,
    });
  },
  childTabChange(e) {
    console.log(e);
    let { index } = e.detail;
    this.setData({
      active_child: index,
    });
    this.init();
    this.getChildData();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.isLoadMore) {
      this.getMoreData();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
  async getMoreData() {
    if (!this.data.isLoadMore) return;
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.page >= this.data.total_page) {
      return;
    } else {
      this.setData({
        page: this.data.page + 1,
      });
      let urlStr = "";
      let json = {
        customer_uid: this.options.id,
        page: this.data.page,
      };
      if (this.data.active_child == "0") {
        urlStr = "plugin.cloud-shop.frontend.customer.orderList";
        json.is_refund = 0;
      } else if (this.data.active_child == "1") {
        urlStr = "plugin.cloud-shop.frontend.customer.orderList";
        json.is_refund = 1;
      } else if (this.data.active_child == "2") {
        urlStr = "plugin.cloud-shop.frontend.customer.historyList";
      } else if (this.data.active_child == "3") {
        urlStr = "plugin.cloud-shop.frontend.customer.cartList";
      } else if (this.data.active_child == "4") {
        urlStr = "plugin.cloud-shop.frontend.customer.brandList";
      }
      let { data } = await app._postNetWork({
        url: app.getNetAddresss(urlStr),
        data: json,
      });
      this.data.isLoadMore = true;
      if (data.result) {
        if (this.data.active_child == "0" || this.data.active_child == "1") {
          this.data.dataList = data.data;
          this.setData({
            dataList: data.data.data,
          });
          return;
        } else if (this.data.active_child == "2") {
          let myData = data.data.member_histories;
          let footPrintArr = [];
          footPrintArr[0] = myData[0];
          let datas = this.handlerFootPrint(myData, footPrintArr); //处理数据结构
          datas.map((item, index) => {
            if (
              this.data.dataList[this.data.dataList.length - 1].date_group ===
              datas[0].date_group
            ) {
              let dataGroup =
                this.data.dataList[this.data.dataList.length - 1].goodsList;
              this.data.dataList[this.data.dataList.length - 1].goodsList = [
                ...dataGroup,
                ...item.goodsList,
              ];
              datas.shift();
            }
            this.data.dataList = [...this.data.dataList, ...datas];
            this.setData({
              dataList: this.data.dataList,
            });
          });
          return;
        } else if (this.data.active_child == "3") {
          this.setData({
            dataList: data.data.data,
          });
        } else if (this.data.active_child == "4") {
          this.setData({
            dataList: data.data.data,
          });
        }
      } else {
        app.tips(data.msg);
      }
    }
  },
  async getChildData() {
    let urlStr = "";
    let json = {
      customer_uid: this.options.id,
    };
    if (this.data.active_child == "0") {
      urlStr = "plugin.cloud-shop.frontend.customer.orderList";
      json.is_refund = 0;
    } else if (this.data.active_child == "1") {
      urlStr = "plugin.cloud-shop.frontend.customer.orderList";
      json.is_refund = 1;
    } else if (this.data.active_child == "2") {
      urlStr = "plugin.cloud-shop.frontend.customer.historyList";
    } else if (this.data.active_child == "3") {
      urlStr = "plugin.cloud-shop.frontend.customer.cartList";
    } else if (this.data.active_child == "4") {
      urlStr = "plugin.cloud-shop.frontend.customer.brandList";
    }
    let { data } = await app._postNetWork({
      url: app.getNetAddresss(urlStr),
      data: json,
    });
    if (data.result) {
      if (this.data.active_child == "0" || this.data.active_child == "1") {
        this.setData({
          dataList: data.data.data,
        });
      } else if (this.data.active_child == "2") {
        this.data.dataList = data.data.member_histories;
        let footPrintArr = [];
        footPrintArr[0] = this.data.dataList[0];
        this.data.dataList = this.handlerFootPrint(
          this.data.dataList,
          footPrintArr
        );
        this.setData({
          dataList: this.data.dataList,
        });
      } else if (this.data.active_child == "3") {
        this.setData({
          dataList: data.data.data,
        });
      } else if (this.data.active_child == "4") {
        this.setData({
          dataList: data.data.data,
        });
      }
      this.data.total_page = data.last_page;
      this.data.isLoadMore = true;
    } else {
      app.tips(data.msg);
    }
  },
  handlerFootPrint(datas, footPrintArr) {
    if (datas.length === 0) return [];
    let i = 0;
    datas.map((item, index) => {
      item.goodsList = [];
      item.goods.delId = item.id;
      item.goods.owner_id = item.owner_id;
      item.goods.vip_level_status = item.vip_level_status;
      item.goods.option_price = item.option_price;
      item.dateName = this.getDate(item.date_group);
      if (
        footPrintArr[i].date_group === (datas[index] && datas[index].date_group)
      ) {
        footPrintArr[i].goodsList.push(datas[index].goods);
      } else {
        i++;
        footPrintArr.push(datas[index]);
        footPrintArr[i].goodsList.push(datas[index].goods);
      }
    });
    console.log(footPrintArr, "wwwwww2222222wwwwww");
    return footPrintArr;
  },
  getDate(str) {
    //处理日期时间
    if (!str) return;
    let strArr = str.split("-");
    let year = strArr[0];
    let month = strArr[1].replace("月", "");
    let day = strArr[2];
    let date = (year + "年" + month + "月" + day + "日").toString();
    return date;
  },
  async getData() {
    let json = {
      customer_uid: this.options.id,
      time_type: this.data.active,
    };
    let { data } = await app._postNetWork({
      url: app.getNetAddresss("plugin.cloud-shop.frontend.customer.detail"),
      data: json,
    });
    if (data.result) {
      data.data.last_order_time = this.timestampToTime(data.data.last_order_time);
      this.setData({
        info: data.data,
      });
    } else {
      app.tips(data.msg);
    }
  },
  timestampToTime(timestamp) {
    if (!Number(timestamp) || timestamp == "") {
      return "";
    }
    let date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let Y = date.getFullYear() + "/";
    let M =
      (date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1) + "/";
    let D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
    let h =
      (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
    let m =
      date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    return Y + M + D + h + m;
  },
});
